# Copyright 2008 Ilya Novoselov
#
# This file is part of TyuChat.
#
# TyuChat is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# TyuChat is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with TyuChat.  If not, see <http://www.gnu.org/licenses/>.

import os

from genshi.output import encode, get_serializer
from genshi.template import Context, TemplateLoader
from twisted.web2 import http_headers

loader = TemplateLoader(
    # FIXME: I don't like this
    os.path.join(os.path.dirname(__file__), '..', '..', 'templates'),
    auto_reload=True
)


class Renderer(object):
    def __init__(self, method='html', encoding='utf-8', **options):
    
        opt = options.copy()
        if method == 'html':
            opt.setdefault('doctype', 'html')
        self.method = method
        self.serializer = get_serializer(method, **opt)
        self.encoding = encoding

    def render(self, *args, **data):
        if len(args) != 1:
            raise TypeError("Should be only one positional argument (template)")
        
        template = args[0]
        
        # Gather context variables.
        ctxt = Context()
        ctxt.push(data)
        
        # Render template.
        template = loader.load(template)
        stream = template.generate(ctxt)
        page = encode(self.serializer(stream), method=self.serializer,
                      encoding=self.encoding)
        
        content_type = http_headers.MimeType('text', self.method,
                                             {'charset': self.encoding})
        
        return page, content_type
        
        #return http.Response(stream=page, headers=headers)